package sgd.tp2.server.net.tcp;

import java.io.DataInputStream;
import java.io.IOException;

import sgd.tp2.api.cdr.CDR;
import sgd.tp2.api.cdr.CDRHandlerJSON;
import sgd.tp2.api.logging.Log;
import sgd.tp2.api.net.CDRFormatType;
import sgd.tp2.api.net.CEPType;

public class TCPServerJSON extends TCPServer {

	public TCPServerJSON(CDRFormatType cdrFormatType, int port, CEPType cepType) {
		super(cdrFormatType, port, cepType);
	}

	@Override
	public void run() {
		DataInputStream inStream = null;
		String receivedStr = "";

		try {
			inStream = new DataInputStream(socket.getInputStream());

			while ((receivedStr = inStream.readUTF()) != null) {
				receivedCDR();
				
				handleJSON(receivedStr);
			}

		} catch (IOException e) {
			Log.infoln("");
			Log.warningln("Parou de receber. Servidor terminado");
			stopServer();
			return;
		}
	}

	public void handleJSON(String json) {
		startCDRHandling();
		
		CDR cdr = CDRHandlerJSON.getCDRFromJSON(json);
		handleCDR(cdr);
		
		endCDRHandling(cdr);
	}
}
